package com.tanhua.sso.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private PicUploadService picUploadService;

    public Boolean saveUserInfo(Map<String, String> param, String token) {
        //校验token 在service里面验证
        User user = this.userService.queryUserByToken(token);
        //判断是否为空 为空说明没有这个用户 就返回flase
        if (null == user) {
            return false;
        }
        //token验证为通过 设置用户的数据
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        int insert = this.userInfoMapper.insert(userInfo);
        return insert == 1;
    }

    public Boolean saveUserLogo(MultipartFile file, String token) {
        //校验token 在service里面验证
        User user = this.userService.queryUserByToken(token);
        //判断是否为空 为空说明没有这个用户 就返回flase
        if (null == user) {
            return false;
        }

        try {
            //校验图片是否是人像,如果不是人像就返回flase
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //是人像图片时 就上次到aliyun 的oss
        PicUploadResult result = this.picUploadService.upload(file);
        //要是返回值里面的name 为空 则是上传失败
        if (StringUtils.isEmpty(result.getName())) {
            return false;
        }
        //上传成功时
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        int update = this.userInfoMapper.update(userInfo, queryWrapper);
        return update == 1;
    }
}
